package com.zadtek.sharkRider.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.adapter.CommonAdapter;
import com.zadtek.sharkRider.activity.adapter.OrderDeliveryHelpAdapter;
import com.zadtek.sharkRider.activity.adapter.OrderDeliveryItemAdapter;
import com.zadtek.sharkRider.activity.adapter.ViewHolders;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.DeliveryOrderData;
import com.zadtek.sharkRider.activity.data.OrderDeliveryData;
import com.zadtek.sharkRider.activity.data.QiangDanData;
import com.zadtek.sharkRider.frame.JsonProcessHelper;
import com.zadtek.sharkRider.views.LazyScrollView;
import com.zadtek.sharkRider.views.LazyScrollView.OnScrollListener;
import com.zadtek.sharkRider.views.MyListView;
import com.zadtek.sharkRider.views.OnChanged;

/**
 * 配送中activity
 * 
 * @author Administrator
 * 
 */
public class OrderpsActivity extends BaseActivity implements OnChanged {
	private MyListView deliveryList, help_deliverylist;
	private TextView ordernull;
	OrderDeliveryAdapter deliveryadapter;
	OrderDeliveryHelpAdapter helpadapter;
	private DeliveryOrderData OrderSendList = new DeliveryOrderData();
	OrderAsyncTask mOrderAsyn;
	public static Handler mHandler;
	private String emp_id = "";
	QiangDanData qiangdan;

	private LazyScrollView waterfall_scroll;
	private View mHeaderView;// 头部的控件
	private TextView pulldown_header_text; // 头部面板
	private SharedPreferences sp;
	
	private ArrayList<OrderDeliveryData> psorderlist;	//配送中的订单

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.deliverylist);

		Const.ORDER_FLAGS = 1;// 判断新任务列表是否刷新 0-刷新；1-不刷新
		deliveryList = (MyListView) findViewById(R.id.deliverylist);
		help_deliverylist = (MyListView) findViewById(R.id.help_deliverylist);
		waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);
		ordernull = (TextView) findViewById(R.id.ordernull);
		/**
		 * 头部和底部刷新
		 */
		mHeaderView = findViewById(R.id.mHeaderView);
		pulldown_header_text = (TextView) findViewById(R.id.pulldown_header_text);
		pulldown_header_text.setText("刷新中...");

		if (Common.isNetworkConnected(OrderpsActivity.this)) {
			// showProgressDialog("数据加载中...");
			mHeaderView.setVisibility(View.VISIBLE);
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("sendlist");
		} else {
			closeProgressDialog();
			Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
		}

		mHandler = new Handler() {
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case Const.STATE_START_SUCCESS://
					closeProgressDialog();
					OrderSendList = new DeliveryOrderData();
					OrderSendList = (DeliveryOrderData) msg.obj;
					mHeaderView.setVisibility(View.GONE);

					if (OrderSendList != null && !OrderSendList.equals("")
							&& !OrderSendList.equals("null")) {
						psorderlist = OrderSendList.getOrderdeliverydata();
						if ((!psorderlist.get(0)
								.getStatus01().equals("0") && OrderSendList
								.getOrderdeliverydata() != null)
								|| (!OrderSendList.getNewhelpData().get(0)
										.getStatus().equals("0") && OrderSendList
										.getNewhelpData() != null)) {

							if (psorderlist != null
									&& !psorderlist
											.get(0).getStatus01().equals("0")) {
								getGpsaddr(); // 根据坐标反查地址
								deliveryList.setVisibility(View.VISIBLE);
								ordernull.setVisibility(View.GONE);
								deliveryadapter = new OrderDeliveryAdapter(
										OrderpsActivity.this,
										psorderlist,
										R.layout.deliverylist_item);
								deliveryList.setAdapter(deliveryadapter);

							}else{
								deliveryList.setVisibility(View.GONE);
							}
							if (OrderSendList.getNewhelpData() != null
									&& !OrderSendList.getNewhelpData().get(0)
											.getStatus().equals("0")) {
								help_deliverylist.setVisibility(View.VISIBLE);
								ordernull.setVisibility(View.GONE);
								 helpadapter = new OrderDeliveryHelpAdapter(
										OrderpsActivity.this,
										OrderSendList.getNewhelpData(),
										R.layout.deliveryhelplist_item);
								helpadapter
										.setHelpOnChanged(OrderpsActivity.this);
								help_deliverylist.setAdapter(helpadapter);

							}else{
								help_deliverylist.setVisibility(View.GONE);
							}
							InitLayout();
						} else {
							deliveryList.setVisibility(View.GONE);
							help_deliverylist.setVisibility(View.GONE);
							ordernull.setVisibility(View.VISIBLE);
						}
					} else {
						Common.DisplayToast(OrderpsActivity.this, "暂无数据!", 1);
					}

					break;

				case Const.STATE_START_QIANG://
					closeProgressDialog();
					qiangdan = new QiangDanData();
					qiangdan = (QiangDanData) msg.obj;
					Common.DisplayToast(OrderpsActivity.this,
							qiangdan.getMessage(), 1);
					if (qiangdan.getStatus().equals("1")) {
						if (Common.isNetworkConnected(OrderpsActivity.this)) {
							new OrderAsyncTask().execute("getsum");
							// showProgressDialog("数据加载中...");
							mHeaderView.setVisibility(View.VISIBLE);
							mOrderAsyn = new OrderAsyncTask();
							mOrderAsyn.execute("sendlist");
						} else {
							closeProgressDialog();
							Common.DisplayToast(OrderpsActivity.this,
									"通信失败,请检查网络!", 1);
						}
					} else {
						mHeaderView.setVisibility(View.GONE);
					}
					break;
				case Const.STATE_START_LOCATION://
					closeProgressDialog();
					qiangdan = new QiangDanData();
					qiangdan = (QiangDanData) msg.obj;
					Common.DisplayToast(OrderpsActivity.this,
							qiangdan.getMessage(), 1);
					if (qiangdan.getStatus().equals("200")) {
						if (Common.isNetworkConnected(OrderpsActivity.this)) {
							new OrderAsyncTask().execute("getsum");
							// showProgressDialog("数据加载中...");
							mHeaderView.setVisibility(View.VISIBLE);
							mOrderAsyn = new OrderAsyncTask();
							mOrderAsyn.execute("sendlist");
						} else {
							closeProgressDialog();
							Common.DisplayToast(OrderpsActivity.this,
									"通信失败,请检查网络!", 1);
						}
					} else {
						mHeaderView.setVisibility(View.GONE);
					}
					break;
				case Const.STATE_GETNUM_SUCC: // 获取数量成功
					QiangDanData sumcout = (QiangDanData) msg.obj;
					String status = sumcout.getStatus();
					if (status != null && status.equals("1")) {
						String xincount = sumcout.getNeworder();
						String noget = sumcout.getNoget();
						String nosend = sumcout.getNosend();
						MainActivity.radio_goqh.setText("待取货(" + noget + ")");
						MainActivity.radio_gops.setText("配送中(" + nosend + ")");
					}
					break;
				case Const.STATE_GETNUM_FAIL:
					// Common.DisplayToast(MainActivity.this, "通信失败,请检查网络!", 2);
					break;
				case Const.STATE_START_ERROR://
					closeProgressDialog();
					Common.DisplayToast(OrderpsActivity.this, "获取数据失败", 1);
					break;
				}
			}
		};
	}

	// 根据经纬度获取地址
	private void getGpsaddr() {
		int size = psorderlist.size();
		for (int i = 0; i < size; i++) {
			try {
				OrderDeliveryData dataobj = psorderlist.get(i);
				String phoneaddr = dataobj.getOrderItemList().get(0)
						.getPhone_addr();
				String address_road = dataobj.getAddress_road();
				if (address_road == null || address_road.equals("")
						|| address_road.equals("null")) {
					if (phoneaddr != null && !phoneaddr.equals("")
							&& !phoneaddr.equals("null")) {
						String[] latlng = phoneaddr.split(",");
						double lng = Double.parseDouble(latlng[0]);
						double lat = Double.parseDouble(latlng[1]);
						getgpssAddress(lat, lng, dataobj, i);
					}
				}
			} catch (Exception e) {
			}
		}
	}

	// 初始化面板
	private void InitLayout() {
		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onTop() {
				mHeaderView.setVisibility(View.VISIBLE);
				if (Common.isNetworkConnected(OrderpsActivity.this)) {
					mOrderAsyn = new OrderAsyncTask();
					mOrderAsyn.execute("sendlist");
				} else {
					closeProgressDialog();
					Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
				}
			}

			@Override
			public void onScroll() {
				// 滚动中
			}

			@Override
			public void onBottom() {
			}
		});
	}

	class OrderAsyncTask extends AsyncTask<String, String, String> {
		private QiangDanData countdata;
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String res = "";
			if (params[0].equals("sendlist")) {// 配送中列表数据
				OrderSendList = new DeliveryOrderData();
				OrderSendList = JsonProcessHelper.jsonProcess_getSendorderList(
						"get_rr_help_send_order_list", emp_id);
				if (OrderSendList != null) {
					res = "state_success";
				} else {
					res = "mi_error";
				}
			} else if (params[0].equals("send")) {// 确认收货
				qiangdan = new QiangDanData();
				qiangdan = JsonProcessHelper.jsonProcess_getQsSendFood(
						"qs_send_food", params[1], params[2]);
				if (qiangdan != null) {
					res = "state_qiang";
				} else {
					res = "mi_error";
				}
			} else if (params[0].equals("syg_send")) {// 随意购确认收货
				qiangdan = new QiangDanData();
				qiangdan = JsonProcessHelper.jsonProcess_getQsExSendFood(
						"ex_send_food", params[1], params[2]);
				if (qiangdan != null) {
					res = "state_qiang1";
				} else {
					res = "mi_error";
				}
			}else if (params[0].equals("getsum")) { // 获取数量

				sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
				String uid = sp.getString("uid", "");
				countdata = JsonProcessHelper.jsonProcess_getOrderCount(
						"get_order_count", uid);
				if (null != countdata) {
					res = "get_ok";
				} else {
					res = "ping_me_error";
				}

			}
			return res;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result.equals("state_success")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_SUCCESS;
				msg.obj = OrderSendList;
				mHandler.sendMessage(msg);
			} else if (result.equals("state_qiang")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_QIANG;
				msg.obj = qiangdan;
				mHandler.sendMessage(msg);
			} else if (result.equals("state_qiang1")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_LOCATION;
				msg.obj = qiangdan;
				mHandler.sendMessage(msg);
			} else if (result.equals("mi_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_ERROR;
				mHandler.sendMessage(msg);
			}else if (result.equals("get_ok")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_GETNUM_SUCC;
				msg.obj = countdata;
				mHandler.sendMessage(msg);
			} else if (result.equals("ping_me_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_GETNUM_FAIL;
				mHandler.sendMessage(msg);
			}
		}
	}

	@Override
	public void getChoiceData(String orderid, String empid,int position) {

		showProgressDialog("数据加载中...");
		if (Common.isNetworkConnected(OrderpsActivity.this)) {
			// mHeaderView.setVisibility(View.VISIBLE);
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("send", orderid, empid);
		} else {
			closeProgressDialog();
			Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
		}

	}

	@Override
	public void getHelpChoiceData(String orderid, String empid,int position) {
		showProgressDialog("数据加载中...");
		if (Common.isNetworkConnected(OrderpsActivity.this)) {
			// mHeaderView.setVisibility(View.VISIBLE);
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("syg_send", orderid, empid);
		} else {
			closeProgressDialog();
			Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
		}
	}

	public class OrderDeliveryAdapter extends CommonAdapter<OrderDeliveryData> {

		public OrderDeliveryAdapter(Context context,
				List<OrderDeliveryData> datas, int layoutId) {
			super(context, datas, layoutId);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void convert(ViewHolders holder, final OrderDeliveryData t) {
			TextView newtaskmomey = holder.getView(R.id.delivery_money);
			TextView newtasktime = holder.getView(R.id.delivery_time);
			LinearLayout pslay = holder.getView(R.id.pslay);
			TextView newtask_goods_getaddress = holder
					.getView(R.id.delivery_goods_getaddress);
			TextView getgpsaddr = holder.getView(R.id.getgpsaddr);

			newtaskmomey.setText("￥" + t.getReturnpay());
			if (!t.getAdd_time().equals("") || t.getAdd_time() != null) {
				newtasktime.setText(Common.getStrTime(t.getAdd_time()));
			}
			try {
				String address_road = t.getAddress_road();
				if (address_road == null || address_road.equals("")
						|| address_road.equals("null")) {
					String addrss = t.getGps_addrs();
					if (addrss != null && !addrss.equals("")) {
						getgpsaddr.setText(addrss); // 根据经纬度反查地址
						getgpsaddr.setVisibility(View.VISIBLE);
					} else {
						getgpsaddr.setVisibility(View.GONE);
					}
				} else {
					getgpsaddr.setText(address_road); // 根据经纬度反查地址
					getgpsaddr.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
			}

			newtask_goods_getaddress.setText(t.getSendaddress());
			ListView ItemList = holder.getView(R.id.delivery_itemlist);
			OrderDeliveryItemAdapter itemadapter = new OrderDeliveryItemAdapter(
					mContext, t.getOrderItemList(),
					R.layout.deliverylist_itemlist_item, t.getMain_id(),
					t.getSendaddress());
			itemadapter.setOnChanged(OrderpsActivity.this);
			ItemList.setAdapter(itemadapter);

			pslay.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					if (t.getMain_id() != null && !t.getMain_id().equals("")) {
						Intent intent = new Intent(mContext,
								OrderDetailActivity_.class);
						intent.putExtra("mainid", t.getMain_id());
						intent.putExtra("status", "ps");
						mContext.startActivity(intent);
					}
				}
			});

		}

	}

	// 反查的
	void getgpssAddress(double lat, double lng,
			final OrderDeliveryData dataobj, final int i) {
		GeocodeSearch geocoderSearch = new GeocodeSearch(this);
		geocoderSearch
				.setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
					@Override
					public void onGeocodeSearched(GeocodeResult result,
							int rCode) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onRegeocodeSearched(RegeocodeResult result,
							int rCode) {
						if (rCode == 1000) {
							String formatAddress = result.getRegeocodeAddress()
									.getFormatAddress();
							try {
								dataobj.setGps_addrs(formatAddress);
								psorderlist.set(i, dataobj);
								OrderSendList.setOrderdeliverydata(psorderlist);
								if(deliveryadapter!=null) {
									deliveryadapter.notifyDataSetChanged();
								}

							} catch (Exception e) {
							}
						}
					}
				});
		LatLonPoint lp = new LatLonPoint(lat, lng);
		RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		emp_id = sp.getString("uid", "");
	}

}
